import fetch from 'dva/fetch';
import { message } from 'antd';

function parseJSON(response) {
  return response.json();
}

function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }

  const error = new Error(response.statusText);
  error.response = response;
  throw error;
}

function checkMyStatus(da){
  const {status,message,data}=da;
  if(status>=200&&status<300){
    return data;
  }else if(status==401){
     message.error(message,3);
     setTimeout(" window.location.href='' ",3000);
     return null;
  }else{
    message.error(message,3);
    return null;
  }

}

function showMessage(err){
  message.error(err.message,3);
}

function isEmpty(o){
  if(o==undefined||o==null||o==''){
    return true;
  }else{
    return false;
  }
}

/**
 * Requests a URL, returning a promise.
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 * @return {object}           An object containing either "data" or "err"
 */
export default function request(url, options) {
  const accessToken =  JSON.parse(window.sessionStorage.getItem("accessToken"));
  if(!isEmpty(accessToken)){
    if(isEmpty(options)){
      options={
        headers:{
          "accessToken":accessToken
        }
      }
    }else{
      if(isEmpty(options.headers)){
        options.headers={
          "accessToken":accessToken
        }
      }else{
        options.headers.accessToken=accessToken;
      }
    }
  }
  return fetch(url, options)
    .then(parseJSON)
    .then(data => ({ data:checkMyStatus(data)}))
    .catch(err => ({err}));
}
